import api from './login.js'
import {
  setLoginInfo
} from '../utils/loginInfo.js'

let isRefreshing = true; // 请求锁
const pathArr = ['/app-api/miniapp/auth/login', '/app-api/miniapp/auth/minapp-login', '/app-api/miniapp/auth/logout', 'pages/permissions/index', 'pages/scan/index']; // 不需要登录的路径
function showToastFunc(err) {
  let message = '连接服务器失败'
  if (err.data?.msg) {
    message = err.data?.msg
    if (err.data.code === 401) {
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/index',
        })
        pendings = [];
        isRefreshing = true;
      }, 2000)
    }
  } else {
    switch (err.statusCode) {
      case 400:
        message = "请求错误(400)";
        break;
      case 401:
        message = "未授权，请重新登录(401)";
        break;
      case 403:
        message = "拒绝访问(403)";
        break;
      case 404:
        message = "请求出错(404)";
        break;
      case 408:
        message = "请求超时(408)";
        break;
      case 500:
        message = "服务器错误(500)";
        break;
      case 501:
        message = "服务未实现(501)";
        break;
      case 502:
        message = "网络错误(502)";
        break;
      case 503:
        message = "服务不可用(503)";
        break;
      case 504:
        message = "网络超时(504)";
        break;
      case 505:
        message = "HTTP版本不受支持(505)";
        break;
      default:
        message = `连接出错(${err.statusCode})!`;
    }
  }
  wx.showModal({
    title: '温馨提示',
    content: message,
    confirmText: '我知道',
    showCancel: false,
  })
}

function request({
  method,
  url,
  data,
  options = {
    needLogin: true
  },
  callback
}) {
  const app = getApp();
  const apiUrl = app.globalData.apiUrl;
  const pages = getCurrentPages();
  const router = pages[pages.length - 1]['route']; // 当前路由
  if (pathArr.includes(url) || pathArr.includes(router)) {
    options.needLogin = false; // 当前路径是否需要登录
  }
  return new Promise((resolve) => {
    wx.showLoading()
    const requestBody = {
      url: apiUrl + url,
      header: {
        Authorization: wx.getStorageSync("accessToken") || '',
        "content-type": options.type || 'application/json'
      },
      method,
      data,
      dataType: 'json',
    }
    if (method === 'PATCH') {
      requestBody.responseType = "arraybuffer" // 此处是请求文件流，必须带入的属性
    }
    // 请求主体
    wx.request({
      ...requestBody,
      success(res) {
        if (callback) {
          callback(res.data); //这个代码是第二次请求到请的token后才执行的， callback其实是 第一次请求时的 resolve,而res.data是第二次请求时的结果， 这里面有点类似递归的思想
          return; //这里是有点绕， 自已体会一下， 口才不好，讲不清楚
        }
        if (res.data?.code === 0 || res.data?.constructor === ArrayBuffer) {
          resolve(res.data);
        } else {
          if (res.data?.code === 401 && isRefreshing) {
            const loginInfo = wx.getStorageSync('loginInfo')
            if (loginInfo) {
              api.refreshToken(JSON.parse(loginInfo)).then(async res => {
                if (res.code === 0) {
                  await setLoginInfo(res.data) // 设置登录信息
                  request({
                    method,
                    url,
                    data,
                    options,
                    callback: resolve
                  })
                  isRefreshing = true;
                } else {
                  toLogin(res.data.msg);
                }
              })
            }
            isRefreshing = false
          } else {
            showToastFunc(res)
          }
        }
      },
      fail(err) {
        showToastFunc(err)
        resolve(err.data);
      },
      complete() {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    })
  })
}

// 前往登录页面 清空状态
function toLogin(msg) {
  wx.showToast({
    title: msg || '登录失效,请重新登录',
    icon: "none",
    success: () => {
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/index',
        })
        isRefreshing = true;
      }, 1200);
    }
  })
}

export default request